package com.zzj.ecology.framework.configs.security;

import com.alibaba.fastjson.JSON;
import com.zzj.ecology.commons.consts.Constant;
import com.zzj.ecology.commons.enums.LoginResultEnum;
import com.zzj.ecology.commons.utils.MessageUtils;
import com.zzj.ecology.framework.manager.AsyncManager;
import com.zzj.ecology.framework.manager.async.AsyncTaskFactory;
import com.zzj.ecology.framework.utils.SecurityUtils;
import com.zzj.ecology.system.dto.HttpResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * 屏蔽重定向的登录页面 /login 并返回统一的json格式的返回体给前端。
 * 而实现这一功能的核心就是实现AuthenticationEntryPoint并在WebSecurityConfig中注入，
 * 然后在configure(HttpSecurity http)方法中。
 */

/**
 * @ClassName CustomizeAuthenticationEntryPoint
 * @Description AuthenticationEntryPoint主要是用来处理匿名用户访问无权限资源时的异常（即未登录，或者登录状态过期失效）
 * @Author zhijun zeng at 2020/2/28
 * @Version 1.0
 **/
@Component
public class CustomizeAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Autowired
    private AsyncManager asyncManager;
    @Autowired
    private AsyncTaskFactory asyncTaskFactory;

    @Override
    public void commence(HttpServletRequest req,
                         HttpServletResponse resp,
                         AuthenticationException e) throws IOException, ServletException {

        String username = SecurityUtils.getUsername();
        //username = StringUtils.isEmpty(username) ?  "anonymous" : username;
        asyncManager.execute(asyncTaskFactory.recordLoginInfor(StringUtils.isEmpty(username) ?  "anonymous" : username ,
                Constant.LOGIN_FAIL,new Date(), MessageUtils.message("user.not.found")));//找不到用户

//        resp.setContentType("text/json;charset=utf-8");
        resp.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        resp.getWriter().write(JSON.toJSONString(new HttpResult(LoginResultEnum.USER_NOT_LOGIN)));
    }
}
